# -*- coding: utf-8 -*-
import random
from zc_core.dao.order_pool_dao import OrderPoolDao
from zc_core.util.done_filter import DoneFilter
from scrapy.exceptions import IgnoreRequest
import scrapy
from scrapy import Request
from zc_core.model.items import ItemPoolData, OrderStatus
from zc_core.util.http_util import retry_request
from zc_core.spiders.base import BaseSpider
from guangdong.rules import *


class OrderItemSpider(BaseSpider):
    name = 'order_item'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(OrderItemSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        self.pool_filter = DoneFilter(coll_name='sku_pool')

    def start_requests(self):
        # 处理订单列表
        order_list = OrderPoolDao().get_todo_list(self.batch_no)
        if order_list:
            self.logger.info('目标: %s' % (len(order_list)))
            random.shuffle(order_list)
            for order in order_list:
                order_id = order.get('_id')
                order_batch_no = order.get('batchNo')
                item_url = order.get('url')
                order_time = order.get('orderTime')
                order_dept = order.get('orderDept')
                sp_name = order.get('supplierName')
                cat_name = order.get('catalogName')

                # 采集order明细页
                yield Request(
                    url=item_url,
                    callback=self.parse_order_item,
                    errback=self.error_back,
                    meta={
                        'reqType': 'order',
                        'orderId': order_id,
                        'orderBatchNo': order_batch_no,
                        'orderTime': order_time,
                        'orderDept': order_dept,
                        'supplierName': sp_name,
                        'catalogName': cat_name,
                    },
                    headers={
                        'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
                        'Accept-Encoding': 'gzip, deflate',
                        'Accept-Language': 'zh-CN,zh;q=0.9',
                        'Cache-Control': 'max-age=0',
                        'Proxy-Connection': 'keep-alive',
                        'Upgrade-Insecure-Requests': '1',
                        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.25 Safari/537.36 Core/1.70.3732.400 QQBrowser/10.5.3819.400',
                    },
                    dont_filter=True
                )

    def parse_order_item(self, response):
        meta = response.meta
        order_id = meta.get('orderId')
        order_time = meta.get('orderTime')
        # 处理订单列表
        tp = parse_order_item(response, self.pool_filter)
        item_list = tp[0]
        if item_list:
            self.logger.info('订单: order=%s, item_cnt=%s' % (order_id, len(item_list)))
            # 保存订单明细
            for item in item_list:
                yield item
            # 标记已采
            order_status = OrderStatus()
            order_status['id'] = order_id
            order_status['orderTime'] = order_time
            order_status['batchNo'] = time_to_batch_no(order_time)
            order_status['workStatus'] = 1
            yield order_status

        skus = tp[1]
        if skus and len(skus):
            for item in skus:
                item['batchNo'] = self.batch_no
                yield item
